<?php

/**
 * 西安英贝科技供应商
 * @author chenshubo
 */
namespace App\Service\VendorClient\Shopybkj;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use App\Model\PssModel\ServiceConfig;

class ShopybkjApiClient extends BaseService
{
    protected $config;
    protected $secret_key;
    const account = 'shopybkj';
    public function __construct()
    {
        $this->config = config('api.'.self::account);
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $param = [] )
    {
        $orderInfo      = $param['supplierOrder'];
        $orderItem      = $param['orderGoods'];
        $order          = $param['order'];
        $binfo          = $param['binfo'];
        
        //支付电商平台
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        $enterpriseNum  = $apply_extends['enterpriseNum']??'';
        $enterpriseNum  = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum ;
        if( !isset($this->orderSource[$enterpriseNum]) ) {
            return Normal::returnCode(Normal::FAIL,"支付电商平台编码：【{$enterpriseNum}】未映射，请联系管理员处理");
        }
        
        
        $order_sn       = $orderInfo['supplier_dsn'];
        $deliver_money  = $orderInfo['deliver_money'];
        
        //组装商品数据列表
        $goodsList  = [];
        $productAmt = $TaxAmt = 0 ;
        foreach ($orderItem as $item )
        {
            $supplier_skucode   = $item['supplier_skucode'];
            $quantity           = $item['quantity'];
            $spec_num           = $item['spec_num'];
            $spec_name          = $item['spec_name'];
            $price              = $item['price'];
            $buynum             = bcmul((string)$quantity, (string)$spec_num);
                        
            //商品税率
            $tax                = $item['tax_rate'];
            $tax_rate           = bcadd((string)$tax,'1.0000',4);
            
            //不含税总价
            $goods_price        = bcdiv((string)$price, (string)$tax_rate,2);
            //不含税总价
            $goodsTotalPrice    = bcmul((string)$goods_price, (string)$quantity,2);
            //含税总价
            $priceTotal         = bcmul((string)$price, (string)$quantity,2);
            //总税
            $SummaryTaxAmt      = bcsub((string)$priceTotal, (string)$goodsTotalPrice,2);
            
            $goodsList[] = [
                'sub_order_no'              => $order_sn,
                'outer_sku_id'              => $supplier_skucode,
                'customs_code'              => $this->config['customs_code'],
                'num'                       => $buynum,
                'title'                     => $item['goods_name'],
                'cross_border_trade_mode'   => $this->config['trade_mode'],
                'sku_properties_name'       => $item['goods_name']."({$spec_name})",
                'payment'                   => (string)$goods_price,
                'item_id'                   => $supplier_skucode,
                'discount_price'            => (string)$goods_price,
                'total_fee'                 => $goodsTotalPrice,
                'sku_unique_code'           => $supplier_skucode,
                'outer_item_id'             => $supplier_skucode,
                'tax_total'                 => $SummaryTaxAmt,
                'freight'                   => 0.00,
                'discount'                  => 0.00
            ];
            $productAmt = bcadd((string)$productAmt, (string)$goodsTotalPrice,2);
            $TaxAmt = bcadd((string)$TaxAmt, (string)$SummaryTaxAmt,2);
        }
        
        //订单总金额 = 商品金额 + 税费 + 运费 - 优惠金额
        $orderMoney = bcadd((string)$productAmt, (string)$TaxAmt,2);
        $orderMoney = bcadd((string)$orderMoney, (string)$deliver_money,2);
        
        //获取电商平台映射配置
        $channel_value = ServiceConfig::instance()->getConfigByEventsValue(self::account, ServiceConfig::TYPE_CHANNEL, $EBPCompanyCode);
        if( empty($channel_value) ) {
            return Normal::returnCode(Normal::FAIL,"支付电商平台编码：【{$EBPCompanyCode}】未映射，请联系管理员处理");
        }
        
        //创建订单数据
        $data = [
            'shop_code'             => $channel_value,
            'delivery_address'      => $orderInfo['receive_address'],
            'receiver_name'         => $orderInfo['receive_name'],
            'delivery_province'     => $orderInfo['province'],
            'delivery_city'         => $orderInfo['city'],
            'delivery_district'     => $orderInfo['district'],
            'receiver_tel'          => $orderInfo['recveive_phone'],
            'post_fee'              => $deliver_money,
            'buyer_phone'           => $orderInfo['buyer_phone'],
            'buyer_id'              => $binfo['bid'],
            'tid'                   => $order_sn,
            'id_card_number'        => $orderInfo['buyer_idcard'],//身份证信息
            'id_card_name'          => $orderInfo['buyer_realname'],//身份证姓名信息
            'created'               => date("Y-m-d H:i:s",$orderInfo['cd']),//订单创建时间 2020-02-29 20:46:42
            'pay_info_payment'      => $orderInfo['real_total_money'],
            'shop'                  => $goodsList
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        $res = $this->execute($requestParam);
        if ($res['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $order_sn
            ]);
        }
        return $res;
    }
    
    /**
     * 获取sign参数
     */
    private function getSign( $param = [] )
    {
        return base64_encode(md5(json_encode($param,JSON_UNESCAPED_UNICODE).$this->config['SECRET_KEY'],true));
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $sign = $this->getSign($param['data']);
        $data = [
            'appkey'    => $this->config['APP_KEY'],
            'token'     => $this->config['TOKEN'],
            'sign'      => $sign,
            'content'   => json_encode($param['data'],JSON_UNESCAPED_UNICODE)
        ];
        $method     = $param['method'];
        $url        = $this->config['API_DOMAIN'].$this->config['api_route'][$method];
        $parameter = [
            [
                'tag'       => self::account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'form-data',
                'header'    => [],
            ],
        ];
        $resTask    = TaskWorker::instance()->addTask($parameter);
        $resTask    = current($resTask);
        $resHttp    = @json_decode($resTask['response']['result'], true);
        $errorMsg   = $resHttp['msg'] ?? '请求失败';
        if (isset($resHttp['code']) && $resHttp['code'] == '2000') {
            return Normal::returnCode(Normal::SUC, "操作成功", $resHttp);
        }
        return Normal::returnCode(Normal::FAIL, $errorMsg);
    }
}